package com.sywb.chuangyebao.contract;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.MediaStoreInfo;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.view.video.PublishVideoPlayer;

import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerDivider;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.log.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 通过相册视频发布
 * Created by duxl on 2018/5/17.
 */

public interface PublishVideoFromPhotoContract {

    interface View extends BaseRecyclerContract.View {
        SurfaceView getSurfaceView();
        ProgressBar getProgressBar();
        SeekBar getSeekBar();
        ImageView getIvPlay();
        TextView getCurrentPositionView();
        TextView getTotalDurationView();
        void showNextBtn(int visible);
    }

    class Presenter extends BaseRecyclerContract.Presenter<View> implements PublishVideoPlayer.OnProgressChangeListner, android.view.View.OnTouchListener, SeekBar.OnSeekBarChangeListener, IAliyunVodPlayer.OnPreparedListener {

        VideoAdapter mAdapter;
        int mDividerWidth;
        PublishVideoPlayer mVideoPlayer;

        @Override
        public void onStart() {
            super.onStart();
            mDividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mActivity.getResources().getDimension(R.dimen.dp_2), mActivity.getResources().getDisplayMetrics());
            recyclerDivider = new BaseRecyclerDivider(false,mDividerWidth, Color.BLACK);
            recyclerDivider.setIncludeStartEdge(false);
            commonRecycler.addItemDecoration(recyclerDivider);

            mView.getIvPlay().setEnabled(false);
            mView.getSeekBar().setEnabled(false);
            mView.getSeekBar().setOnSeekBarChangeListener(this);
            mView.getProgressBar().setVisibility(android.view.View.GONE);
            mVideoPlayer = new PublishVideoPlayer(mContext, mView.getSurfaceView());
            mVideoPlayer.setOnProgressChangeListner(this);
            mVideoPlayer.setOnPreparedListener(this);
            mVideoPlayer.setSurfaceView(mView.getSurfaceView());

            initData();
        }

        @Override
        public void initData() {
            List<MediaStoreInfo> listData = getMediaInfoData();
            if(listData != null) {
                mAdapter = new VideoAdapter(mActivity, useGridLayoutManagerColumns());
                mAdapter.notifyDataChangedAfterLoadMore(listData);
                setRecyclerAdapter(mAdapter, false);
            }
        }

        @Override
        public int useRecyclerLayoutManager() {
            return 2;
        }

        private List<MediaStoreInfo> getMediaInfoData() {
            List<MediaStoreInfo> listData = null;

            ContentResolver contentResolver= mActivity.getContentResolver();
            Uri uri= MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            String[] projection={
                    MediaStore.Video.Media.DISPLAY_NAME,//视频在sd卡中的名称
                    MediaStore.Video.Media.DURATION,//视频时长
                    MediaStore.Video.Media.DATA,//视频的绝对路径
                    MediaStore.Video.Media.SIZE,//视频文件的大小
                    MediaStore.Video.Media.ARTIST,//艺术家
                    MediaStore.Video.Media._ID
            };
            String[] thumbColumns = new String[]{
                    MediaStore.Video.Thumbnails.DATA, // 缩略图
                    MediaStore.Video.Thumbnails.VIDEO_ID
            };

            //  筛选相册条件
            String selection = MediaStore.Video.Media.DURATION + ">=? and " + MediaStore.Video.Media.DURATION + "<=?";
            int minDuration = mContext.getResources().getInteger(R.integer.video_min_duration);
            int maxDuration = mContext.getResources().getInteger(R.integer.video_max_duration);
            String[] selectionArgs = {String.valueOf(minDuration), String.valueOf(maxDuration)};

            // 最新视频排前面
            String sortOrder =  MediaStore.Video.Media.DATE_ADDED + " desc";

            Cursor cur = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            if(cur != null) {
                listData = new ArrayList<>();
                while(cur.moveToNext()) {
                    MediaStoreInfo mediaInfo = new MediaStoreInfo();
                    mediaInfo.name = cur.getString(cur.getColumnIndex(projection[0]));
                    mediaInfo.duration = cur.getLong(cur.getColumnIndex(projection[1]));
                    mediaInfo.path = cur.getString(cur.getColumnIndex(projection[2]));
                    mediaInfo.size = cur.getLong(cur.getColumnIndex(projection[3]));

//                    String selection = MediaStore.Video.Thumbnails.VIDEO_ID +"=?";
//                    String[] selectionArgs = new String[]{
//                            "" + cur.getInt(cur.getColumnIndex(projection[5]))
//                    };
//
//                    Cursor thumbCursor = contentResolver.query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, thumbColumns, selection, selectionArgs, null);
//                    if(thumbCursor.moveToFirst()){
//                        mediaInfo.thumbPath = thumbCursor.getString(thumbCursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA));
//                    }
//                    thumbCursor.close();

                    listData.add(mediaInfo);
                }

                cur.close();
            }

            return listData;
        }

        public void play() {
            try {
                mVideoPlayer.play();
            } catch (Exception e) {
                Logger.e(e.getMessage());
                mView.showMessage(e.getMessage());
            }
        }

        public void pause() {
            mVideoPlayer.pause();
        }

        public boolean isPlaying() {
            return mVideoPlayer.getPlayerState() == IAliyunVodPlayer.PlayerState.Started;
        }
        @Override
        public void onProgressChanged(int current, int total) {
            if(mView == null) {
                return;
            }
            if(mView.getSeekBar().getTag() == null) {
                mView.getSeekBar().setMax(total);
                mView.getSeekBar().setProgress(current);
                mView.getTotalDurationView().setText(DateTimeUtils.formatTime(total));
                mView.getCurrentPositionView().setText(DateTimeUtils.formatTime(current));
            }

        }

        @Override
        public void onPrepared() {
            mView.getIvPlay().setEnabled(true);
            mView.getSeekBar().setEnabled(true);
            mView.getProgressBar().setVisibility(android.view.View.GONE);
        }

        public MediaStoreInfo getSelectedMedia() {
            if(mAdapter != null && mAdapter.checkedPosition != -1) {
                return mAdapter.getItem(mAdapter.checkedPosition);
            }
            return null;
        }

        @Override
        public boolean onTouch(android.view.View v, MotionEvent event) {
            return false;
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(fromUser) {
                mView.getCurrentPositionView().setText(DateTimeUtils.formatTime(progress));
                mVideoPlayer.seekTo(progress/1000);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            seekBar.setTag("fromUser");
            mVideoPlayer.pause();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            seekBar.setTag(null);
            play();
        }

        class VideoAdapter extends BaseRecyclerAdapter<MediaStoreInfo> {

            int itemHeight;
            public int checkedPosition = -1;

            public VideoAdapter(Context context, int column) {
                super(context, R.layout.adapter_video_from_photo);
                itemHeight = (ScreenUtils.getScreenWidth(mContext) - mDividerWidth * (column-1)) / column;
            }

            @Override
            protected android.view.View onCreateDefView(ViewGroup parent, int viewType) {
                android.view.View defView = super.onCreateDefView(parent, viewType);
                defView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight));
                return defView;
            }

            @Override
            protected void setItemData(ViewHolderHelper viewHolderHelper, int i, MediaStoreInfo mediaStoreInfo) {
                viewHolderHelper.setVisibility(R.id.ivChecked_adapter_video_from_photo, i == checkedPosition);
                ImageView ivImg = viewHolderHelper.getView(R.id.ivImg_adapter_video_from_photo);
                Glide.with(mContext).load(new File(mediaStoreInfo.path)).into(ivImg);
                viewHolderHelper.setText(R.id.tvTime_adapter_video_from_photo, DateTimeUtils.formatTime((int) mediaStoreInfo.duration));
            }
        }

        @Override
        public void onRecyclerItemClick(int position) {
            if(mAdapter.checkedPosition != position) {
                mAdapter.checkedPosition = position;
                mAdapter.notifyDataSetChanged();
                MediaStoreInfo mediaInfo = mAdapter.getDatas().get(position);
                mVideoPlayer.setSource(mediaInfo.path);
                mView.showNextBtn(android.view.View.VISIBLE);
                mView.getIvPlay().setEnabled(false);
                mView.getSeekBar().setEnabled(false);
                mView.getProgressBar().setVisibility(android.view.View.VISIBLE);

                play();
            }
        }
    }
}
